package com.example.shanguigu.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * 分散读与聚集写
 */
public class NIOScatteringAndGathering {
    public static void main(String[] args) throws Exception{
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress address = new InetSocketAddress(7000);

        serverSocketChannel.socket().bind(address);

        ByteBuffer[] buffers = new ByteBuffer[2];
        buffers[0]=ByteBuffer.allocate(5);
        buffers[1]=ByteBuffer.allocate(3);

        SocketChannel socketChannel = serverSocketChannel.accept();
        int maxLen=8;
        while (true){
            int read=0;

            while (read<maxLen){
                long read1 = socketChannel.read(buffers);
                read+=read1;
                System.out.println("read = " + read);
                Arrays.asList(buffers).stream().map(byteBuffer -> "position=" +
                        byteBuffer.position()+", limit= "+byteBuffer.limit())
                        .forEach(System.out::println);
            }

            for (ByteBuffer buffer : buffers) {
                buffer.flip();
            }

            long write=0;
            while (write<maxLen){
                long write1 = socketChannel.write(buffers);
                write+=write1;
            }
            for (ByteBuffer buffer : buffers) {
                buffer.clear();
            }

            System.out.println("read=" +read + " write="+write+" maxLen="+maxLen);
        }
    }
}
